<?php
namespace app\api\controller;
use think\Db;
use think\request;
use think\Controller;
use app\common\controller\ApiBaseController;

class Index extends ApiBaseController
{
	protected function _initialize() {
		parent::_initialize();
	}
	/**
 	 * POST
	 * 会员登录
	 */
	public function login(){
        $where['mobile'] = input('mobile');
		//file_put_contents("a.txt", input());
		$where['password'] = md5_salt(input('password'));
		$where['state'] = 1;
        $member = db('agent_clerk')->where($where)->find();
        if (!empty($member)) {
            if ($member['state']==2) {
                return json(["code"=>408,"msg"=>'用户已经禁用']);
            } else {
				return json(["code"=>200,"msg"=>'登录成功',"member"=>$member]);
            }
        } else {
			return json(["code"=>408,"msg"=>'用户或密码错误']);
        }
	}
	
	//发送短信
	function test_sms(){
		
		//获取对应的短信模板
		$template = db('sms_template') ->where('id',4)->find();
		//短信模板所需参数
		$msg['name'] = $paylog[0]['price'];
		
		//发送短信
		$msg = send_sms('15343353867', $template['tid'], json_encode($msg), $template['sign_name']);
	}
	
	/**
	 * 判断用户是否关注过公众号
	 */
	function is_atten($openid){
		$we_config = get_config('payment_config');
		$access_token=$this->getToken($we_config);
//		$openid=input("openid");
		$res=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		if(isset($array1['nickname'])){
			db('info_user')->where('openid',$openid)->update(["is_atten"=>1]);
			return json(["code"=>200]);
		}else{
			return json(["code"=>400]);
		}
	}
	
	//获取token
	public function getToken($we_config){
		$cache = cache('access_token');
		if ($cache && $cache['token'] && $cache['expire'] > time()) {
			return $cache['token'];
		}
		$appid=$we_config['wxpay_appid'];
		$appsecret=$we_config['wxpay_appsercet'];
		$rurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
		$weixin =  file_get_contents($rurl);
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		if($array['access_token']){
			$record = array();
			$record['token'] = $array['access_token'];
			$record['expire'] = time() + 7000;
			cache('access_token', $record, $record['expire']);
			return $array['access_token'];
		}else{
			return json(['code'=>406,'msg'=>'获取微信公众号授权失败！错误代码:'.$array['errcode']]);
		}		
	}
}
